//
//  RunViewController.m
//  享动
//
//  Created by lanou on 16/4/7.
//  Copyright © 2016年 HHUI. All rights reserved.



#import "RunViewController.h"
#import <MapKit/MapKit.h>
#import "PlaceModel.h"
#import "CLLocation+YCLocation.h"
#import "MusicChooseViewController.h"

@interface RunViewController ()<CLLocationManagerDelegate,MKMapViewDelegate, UITableViewDataSource, UITableViewDelegate>

@property (nonatomic,strong)CLLocationManager *locationManager;
@property (nonatomic,strong)MKMapView *mapView;
@property (nonatomic,strong)NSMutableArray *rePlayArray;
@property(nonatomic, strong)  CLLocation *currLocation;
@property(nonatomic, strong)  MKPolyline *routeLine;
@property(nonatomic, strong)  MKPolylineView *routeLineView;
@property (nonatomic, strong) UIView *beginView;
@property (nonatomic, strong) UIView *afterView;

// 点击开始之后的界面
@property (nonatomic, strong) UILabel *allTimeLabel;
@property (nonatomic, strong) UILabel *speedLabel;
@property (nonatomic, strong) UILabel *lengthLabel;

// 开始结束按钮
@property (nonatomic, strong) UIButton *startRun;
@property (nonatomic, strong) UIButton *stopRun;

// 开始界面
@property (nonatomic, strong) UILabel *allNumber;
@property (nonatomic, strong) UILabel *allMileage;
@property (nonatomic, strong) UIView *countdownView;
@property (nonatomic, strong) UILabel *countdownLabel;
@property (nonatomic, assign) NSInteger time;

@property (nonatomic, assign) NSTimer *timerRun;
@property (nonatomic, assign) NSInteger runingTime;

@property (nonatomic, strong) UIButton *finishButton;
@property (nonatomic, strong) UIButton *continueButton;

@property (nonatomic, assign) BOOL isRun;

// 记录老位置
@property (nonatomic, strong) CLLocation * oldLocation;
// 记录距离差
@property (nonatomic, assign) CLLocationDistance meters;
@property (nonatomic, assign) CGFloat allMeters;

// 记录次数
@property (nonatomic, assign) NSInteger NumberTime;

@property (nonatomic, strong) UIAlertController *alertController;

@property (nonatomic, strong) UIView *setView;

@property (nonatomic, strong) NSTimer *animationTimer;

// 设置按钮出来的view
@property (nonatomic, strong) UIView *musicView;

@property (nonatomic, strong) UIView *backView;

@property (nonatomic, strong) UITableView *tabelView;

@property (nonatomic, assign) BOOL isDik;
@end

@implementation RunViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    _rePlayArray=[[NSMutableArray alloc] init];
    _mapView=[[MKMapView alloc]initWithFrame:CGRectMake(0, 64, KWIDTH, KHEIGHT - 64)];
    _mapView.delegate = self;
    _mapView.showsUserLocation = YES;
//    _mapView.userInteractionEnabled = NO;
//    _mapView.scrollEnabled = YES;
    _mapView.userTrackingMode = MKUserTrackingModeFollowWithHeading;
    
    [self.view addSubview:_mapView];

    
    [self configureLocationManager];
    
  //  [self drawLineWithLocationArray:_rePlayArray];
    
    
    _startRun = [[UIButton alloc]initWithFrame:CGRectMake(KWIDTH / 2 - 70, KHEIGHT - 120, 140, 40)];
    _startRun.backgroundColor = [UIColor colorWithRed:128/255.0 green:197/255.0 blue:56/255.0 alpha:1];
    _startRun.layer.cornerRadius = 15;
    [_startRun setTitle:@"开始跑步" forState:UIControlStateNormal];
    [_startRun addTarget:self action:@selector(startRunAction) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_startRun];
    
    _stopRun = [[UIButton alloc]initWithFrame:CGRectMake(KWIDTH / 2 - 25, KHEIGHT, 50, 50)];
    _stopRun.layer.cornerRadius = 25;
    _stopRun.backgroundColor = [UIColor redColor];
    [_stopRun setTitle:@"暂停" forState:UIControlStateNormal];
    [_stopRun addTarget:self action:@selector(stopAction) forControlEvents:UIControlEventTouchUpInside];
//    _stopRun.hidden = YES;
//    [_stopRun addTarget:self action:@selector(stopAction) forControlEvents:UIControlEventTouchUpInside];
    // 轻扫手势
    UISwipeGestureRecognizer *swipe = [[UISwipeGestureRecognizer alloc]initWithTarget:self action:@selector(stopAction)];
    // 设置轻扫方向
    swipe.direction = UISwipeGestureRecognizerDirectionDown;
    [_stopRun addGestureRecognizer:swipe];
    [self.view addSubview:_stopRun];
    
    // 左边定位栏
    UIView *positioningView = [[UIView alloc]initWithFrame:CGRectMake(-40, KHEIGHT - 120, 80, 40)];
    positioningView.backgroundColor = [UIColor whiteColor];
    positioningView.layer.cornerRadius = 20;
    [self.view addSubview:positioningView];
    
    UIButton *locationButton = [[UIButton alloc]initWithFrame:CGRectMake(50, 10, 20, 20)];
    locationButton.layer.cornerRadius = 10;
    [locationButton setImage:[UIImage imageNamed:@"location-1"] forState:UIControlStateNormal];
    [locationButton addTarget:self action:@selector(loactionAction) forControlEvents:UIControlEventTouchUpInside];
    [positioningView addSubview:locationButton];
    
    // 设置按钮
    _setView = [[UIView alloc]initWithFrame:CGRectMake(KWIDTH, KHEIGHT - 120, 80, 40)];
    _setView.backgroundColor = [UIColor whiteColor];
    _setView.layer.cornerRadius = 20;
    // _setView.hidden = YES;
    [self.view addSubview:_setView];
    
    UIButton *setButton = [[UIButton alloc]initWithFrame:CGRectMake(10, 10, 20, 20)];
    setButton.layer.cornerRadius = 10;
//    setButton.backgroundColor = [UIColor redColor];
    [setButton setImage:[UIImage imageNamed:@"19-gear"] forState:UIControlStateNormal];
    [setButton addTarget:self action:@selector(setButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    [_setView addSubview:setButton];
    
    
    _finishButton = [[UIButton alloc]initWithFrame:CGRectMake(0, KHEIGHT - 39, KWIDTH / 2, 39)];
    _finishButton.backgroundColor = [UIColor redColor];
    _finishButton.alpha = 0.7;
    [_finishButton setTitle:@"完成" forState:UIControlStateNormal];
    [_finishButton addTarget:self action:@selector(finishAction) forControlEvents:UIControlEventTouchUpInside];
    
    _continueButton = [[UIButton alloc]initWithFrame:CGRectMake(KWIDTH / 2, KHEIGHT -  39, KWIDTH / 2, 39)];
    _continueButton.backgroundColor = [UIColor colorWithRed:65/255.0 green:174/255.0 blue:57/255.0 alpha:1];
    _continueButton.alpha = 0.7;
    [_continueButton setTitle:@"继续" forState:UIControlStateNormal];
    [_continueButton addTarget:self action:@selector(continueAction) forControlEvents:UIControlEventTouchUpInside];
    _finishButton.hidden = YES;
    _continueButton.hidden = YES;
    [self.view addSubview:_finishButton];
    [self.view addSubview:_continueButton];
    
    // 没开始跑步时候的界面
    [self numberView];
    
    
    
}

#pragma mark ---- 没点击开始跑步的界面 ---
- (void)numberView
{
    self.navigationItem.title = @"训练";
    _beginView = [[UIView alloc]initWithFrame:CGRectMake(10, 74, KWIDTH - 20, 120)];
    _beginView.backgroundColor = [UIColor whiteColor];
    _beginView.layer.shadowOffset = CGSizeMake(5, 5);
    _beginView.layer.shadowOpacity = 0.6;
    _beginView.layer.shadowColor = [UIColor blackColor].CGColor;
    [self.view addSubview:_beginView];
    
    UILabel *allNmuber1 = [[UILabel alloc]initWithFrame:CGRectMake(30, 20, 50, 20)];
    allNmuber1.text = @"总次数";
    allNmuber1.font = [UIFont systemFontOfSize:13];
    allNmuber1.textColor = [UIColor grayColor];
    [_beginView addSubview:allNmuber1];
    
    _allNumber = [[UILabel alloc]initWithFrame:CGRectMake(30, 50, 80, 40)];
//    _allNumber.backgroundColor = [UIColor grayColor];
    _allNumber.textColor = [UIColor colorWithRed:65/255.0 green:174/255.0 blue:57/255.0 alpha:1];
    _allNumber.font = [UIFont systemFontOfSize:40];
    [[NSUserDefaults standardUserDefaults]setObject:[NSString stringWithFormat:@"%ld", _NumberTime] forKey:@"numberTime"];

    _NumberTime = [[[NSUserDefaults standardUserDefaults]objectForKey:@"numberTime"] intValue];
    _allNumber.text = [NSString stringWithFormat:@"%ld", _NumberTime];
    [_beginView addSubview:_allNumber];
    
    UILabel *allMileage1 = [[UILabel alloc]initWithFrame:CGRectMake(KWIDTH - 20 - 30 - 70, 20, 70, 20)];
    allMileage1.text = @"总里程(km)";
    allMileage1.font = [UIFont systemFontOfSize:13];
    allMileage1.textColor = [UIColor grayColor];
    [_beginView addSubview:allMileage1];
    
    _allMileage = [[UILabel alloc]initWithFrame:CGRectMake(KWIDTH - 20 - 15 - 90, 50, 90, 40)];
    _allMileage.text = @"0.00";
    _allMileage.textColor = [UIColor colorWithRed:65/255.0 green:174/255.0 blue:57/255.0 alpha:1];
    _allMileage.font = [UIFont systemFontOfSize:40];
    [[NSUserDefaults standardUserDefaults]setObject:[NSString stringWithFormat:@"%.2f", _allMeters / 1000] forKey:@"allMeters"];
    _allMeters = [[[NSUserDefaults standardUserDefaults]objectForKey:@"allMeters"] floatValue];

    _allMileage.text = [NSString stringWithFormat:@"%.2f", _allMeters];
    [_beginView addSubview:_allMileage];
    
}

#pragma mark ---- 点击开始跑步的界面 ---
- (void)timeView
{
    
    self.navigationItem.title = @"跑步中...";
    
   _afterView = [[UIView alloc]initWithFrame:CGRectMake(10, 74, KWIDTH - 20, 120)];
    _afterView.backgroundColor = [UIColor whiteColor];
    _afterView.layer.shadowOffset = CGSizeMake(5, 5);
    _afterView.layer.shadowOpacity = 0.6;
    _afterView.layer.shadowColor = [UIColor blackColor].CGColor;
    [self.view addSubview:_afterView];
    
    _allTimeLabel = [[UILabel alloc]initWithFrame:CGRectMake((KWIDTH - 20) / 2 - 90, 20, 180, 40)];
//    _allTimeLabel.backgroundColor = [UIColor grayColor];
    _allTimeLabel.text = @"00:00:00";
    _allTimeLabel.textColor = [UIColor colorWithRed:65/255.0 green:174/255.0 blue:57/255.0 alpha:1];
    _allTimeLabel.textAlignment = NSTextAlignmentCenter;
    _allTimeLabel.font = [UIFont systemFontOfSize:40];
    [_afterView addSubview:_allTimeLabel];
    
    UILabel *allTime1Label = [[UILabel alloc]initWithFrame:CGRectMake((KWIDTH - 20) / 2 + 95, 40, 35, 20)];
    //    allTime1Label.backgroundColor = [UIColor grayColor];
    allTime1Label.text = @"时长";
    allTime1Label.textColor = [UIColor colorWithRed:128/255.0 green:197/255.0 blue:56/255.0 alpha:1];
    allTime1Label.font = [UIFont systemFontOfSize:15];
    [_afterView addSubview:allTime1Label];
    
    UIView *lineView = [[UIView alloc]initWithFrame:CGRectMake(0, 70, KWIDTH - 20, 1)];
    lineView.backgroundColor = [UIColor grayColor];
    lineView.alpha = 0.4;
    [_afterView addSubview:lineView];
    
    UILabel *speed1Label = [[UILabel alloc]initWithFrame:CGRectMake(30, 75, 100, 20)];
    speed1Label.text = @"配速(km/min )";
    speed1Label.textColor = [UIColor colorWithRed:128/255.0 green:197/255.0 blue:56/255.0 alpha:1];
    speed1Label.textAlignment = NSTextAlignmentCenter;
    //    speed1Label.backgroundColor = [UIColor grayColor];
    speed1Label.font = [UIFont systemFontOfSize:13];
    [_afterView addSubview:speed1Label];
    
    _speedLabel = [[UILabel alloc]initWithFrame:CGRectMake(50, 96, 60, 20)];
    _speedLabel.text = @"0:00";
    //    _speedLabel.backgroundColor = [UIColor grayColor];
    _speedLabel.textAlignment = NSTextAlignmentCenter;
    _speedLabel.textColor = [UIColor colorWithRed:65/255.0 green:174/255.0 blue:57/255.0 alpha:1];
    [_afterView addSubview:_speedLabel];
    
    
    
    UILabel *length1Label = [[UILabel alloc]initWithFrame:CGRectMake((KWIDTH - 20) - 30 - 100, 75, 100, 20)];
    length1Label.text = @"距离(km)";
    length1Label.textColor = [UIColor colorWithRed:128/255.0 green:197/255.0 blue:56/255.0 alpha:1];
    //    length1Label.backgroundColor = [UIColor grayColor];
    length1Label.font = [UIFont systemFontOfSize:13];
    length1Label.textAlignment = NSTextAlignmentCenter;
    [_afterView addSubview: length1Label];
    
    _lengthLabel = [[UILabel alloc]initWithFrame:CGRectMake((KWIDTH - 20) - 50 - 60, 96, 60, 20)];
    _lengthLabel.text = @"0.00";
    //    _lengthLabel.backgroundColor = [UIColor grayColor];
    _lengthLabel.textColor = [UIColor colorWithRed:65/255.0 green:174/255.0 blue:57/255.0 alpha:1];
    _lengthLabel.textAlignment = NSTextAlignmentCenter;
    [_afterView addSubview:_lengthLabel];
    
    // 背景图
    _backView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, KWIDTH, KHEIGHT)];
    _backView.backgroundColor = [UIColor blackColor];
    _backView.alpha = 0.3;
    _backView.hidden = YES;
    [self.view addSubview:_backView];
    
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapAction)];
    [_backView addGestureRecognizer:tap];
    
    // 用来点击设置弹出的视图
    _musicView = [[UIView alloc]initWithFrame:CGRectMake(0, KHEIGHT, KWIDTH, 170)];
    _musicView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:_musicView];
    
    UIButton *chooseButton = [[UIButton alloc]initWithFrame:CGRectMake(KWIDTH / 3 / 2 - 20, 20, 40, 40)];
    chooseButton.backgroundColor = [UIColor grayColor];
    chooseButton.layer.cornerRadius = 20;
    [chooseButton addTarget:self action:@selector(chooseButtonAction) forControlEvents:UIControlEventTouchUpInside];
    [_musicView addSubview:chooseButton];
    UILabel *chooseLabel = [[UILabel alloc]initWithFrame:CGRectMake(KWIDTH / 3 / 2 - 50, 70, 100, 20)];
    chooseLabel.text = @"选择音乐";
    chooseLabel.textAlignment = NSTextAlignmentCenter;
    chooseLabel.textColor = [UIColor colorWithRed:128/255.0 green:197/255.0 blue:56/255.0 alpha:1];
    [_musicView addSubview:chooseLabel];
    
    
    UIButton *playButton = [[UIButton alloc]initWithFrame:CGRectMake(KWIDTH / 3 + KWIDTH / 3 / 2 - 20, 20, 40, 40)];
    playButton.backgroundColor = [UIColor grayColor];
    playButton.layer.cornerRadius = 20;
    [playButton addTarget:self action:@selector(playButtonAction) forControlEvents:UIControlEventTouchUpInside];
    [_musicView addSubview:playButton];
    
    UILabel *playLabel = [[UILabel alloc]initWithFrame:CGRectMake(KWIDTH / 3 + KWIDTH / 3 / 2 - 50, 70, 100, 20)];
    playLabel.text = @"屏幕常亮";
    playLabel.textAlignment = NSTextAlignmentCenter;
    playLabel.textColor = [UIColor colorWithRed:128/255.0 green:197/255.0 blue:56/255.0 alpha:1];
    [_musicView addSubview:playLabel];
    
    UIButton *mapButton = [[UIButton alloc]initWithFrame:CGRectMake(KWIDTH / 3 * 2 + KWIDTH / 3 / 2 - 20, 20, 40, 40)];
//    mapButton.backgroundColor = [UIColor grayColor];
    mapButton.layer.cornerRadius = 20;
    [mapButton setImage:[UIImage imageNamed:@"map"] forState:UIControlStateNormal];
    [mapButton addTarget:self action:@selector(mapButtonAction) forControlEvents:UIControlEventTouchUpInside];
    [_musicView addSubview:mapButton];
    
    UILabel *mapLabel = [[UILabel alloc]initWithFrame:CGRectMake(KWIDTH / 3 * 2 + KWIDTH / 3 / 2 - 50, 70, 100, 20)];
    mapLabel.text = @"选择地图";
    mapLabel.textAlignment = NSTextAlignmentCenter;
    mapLabel.textColor = [UIColor colorWithRed:128/255.0 green:197/255.0 blue:56/255.0 alpha:1];
    [_musicView addSubview:mapLabel];
    
    UIButton *backButton = [[UIButton alloc]initWithFrame:CGRectMake(10, 120, KWIDTH -20, 40)];
    backButton.backgroundColor = [UIColor colorWithRed:128/255.0 green:197/255.0 blue:56/255.0 alpha:1];
    [backButton setTitle:@"返回" forState:UIControlStateNormal];
    [backButton addTarget:self action:@selector(tapAction) forControlEvents:UIControlEventTouchUpInside];
    backButton.layer.cornerRadius = 5;
    [_musicView addSubview:backButton];
    
    
    _tabelView = [[UITableView alloc]initWithFrame:CGRectMake(KWIDTH / 3 * 2 + KWIDTH / 3 / 2, KHEIGHT - 120, 0, 0)];
    _tabelView.delegate = self;
    _tabelView.dataSource = self;
    _tabelView.rowHeight = 26;
    _tabelView.backgroundColor = [UIColor whiteColor];
    _tabelView.alpha = 0.7;
    [_tabelView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"cell"];
    [self.view addSubview:_tabelView];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 3;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell" forIndexPath:indexPath];
    if (indexPath.row == 0) {
        cell.textLabel.text = @"标准地图";

    } else if (indexPath.row == 1) {
        cell.textLabel.text = @"卫星地图";
    } else if (indexPath.row == 2) {
        cell.textLabel.text = @"混合地图";
    }
    cell.textLabel.textAlignment = NSTextAlignmentCenter;
    cell.textLabel.textColor = [UIColor colorWithRed:65/255.0 green:174/255.0 blue:57/255.0 alpha:1];
//    cell.backgroundColor = [UIColor clearColor];
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row == 0) {
         _mapView.mapType = MKMapTypeStandard;
    } else if (indexPath.row == 1) {
         _mapView.mapType = MKMapTypeSatellite;
    } else if (indexPath.row == 2) {
         _mapView.mapType = MKMapTypeHybrid;
    }
    
    [self tapAction];
}
#pragma mark --- 点击开始跑步的方法 ----
- (void)startRunAction
{
    
    _isRun = YES;
    _time = 4;

    _countdownView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, KWIDTH, KHEIGHT)];
    _countdownView.backgroundColor = [UIColor whiteColor];
    _countdownView.alpha = 0.7;
    
    _countdownLabel = [[UILabel alloc]initWithFrame:CGRectMake(KWIDTH / 2 - 40, KHEIGHT / 2 - 100, 80, 200)];
    _countdownLabel.text = @"3";
    _countdownLabel.textColor = [UIColor colorWithRed:65/255.0 green:174/255.0 blue:57/255.0 alpha:1];
    _countdownLabel.font = [UIFont systemFontOfSize:120];
    _countdownLabel.textAlignment = NSTextAlignmentCenter;

    [UIView animateWithDuration:0.5 animations:^{
        self.navigationController.tabBarController.tabBar.frame = CGRectMake(0, KHEIGHT, KWIDTH, 49);
        [self.view addSubview:_countdownView];
    } completion:^(BOOL finished) {
        [self.view addSubview:_countdownLabel];
        _startRun.hidden = YES;
//        _setView.hidden = NO;
        NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(timeAction:) userInfo:nil repeats:YES];
    }];
    

}
 
- (void)timeAction:(NSTimer *)timer
{
  
    _time--;
    _countdownLabel.text = [NSString stringWithFormat:@"%ld", _time - 1];
    if (_time == 0) {
        [timer invalidate];
        [_countdownView removeFromSuperview];
        [_countdownLabel removeFromSuperview];
        [UIView transitionWithView:_beginView duration:1 options:UIViewAnimationOptionTransitionFlipFromLeft animations:^{
        [UIView animateWithDuration:1 animations:^{
            _stopRun.frame = CGRectMake(KWIDTH / 2 - 25, KHEIGHT - 120, 50, 50);
            _setView.frame = CGRectMake(KWIDTH - 40, KHEIGHT - 120, 80,40);
            }];
        } completion:^(BOOL finished) {
            [_beginView removeFromSuperview];
//            _stopRun.hidden = NO;
            [self timeView];

            _timerRun =[NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(timeRunAction) userInfo:nil repeats:YES];
            _runingTime = 0;
        }];

    }
}


- (void)timeRunAction
{
    _runingTime++;
    _allTimeLabel.text = [NSString stringWithFormat:@"%02ld:%02ld:%02ld", _runingTime / 3600, _runingTime / 60, _runingTime % 60];
    

    
}

#pragma mark ---- 暂停跑步的方法 -----
- (void)stopAction
{
    [_timerRun setFireDate:[NSDate distantFuture]];

    [UIView animateWithDuration:1 animations:^{
        _stopRun.frame = CGRectMake(KWIDTH / 2 - 25, KHEIGHT, 50, 50);
    } completion:^(BOOL finished) {
        _finishButton.hidden = NO;
        _continueButton.hidden = NO;
    }];
    
    _animationTimer = [NSTimer scheduledTimerWithTimeInterval:2 target:self selector:@selector(animation1) userInfo:nil repeats:YES];
}

- (void)animation1
{
    [UIView animateWithDuration:1 animations:^{
        _allTimeLabel.alpha = 0.2;

    } completion:^(BOOL finished) {
        [UIView animateWithDuration:1 animations:^{
            _allTimeLabel.alpha = 1;
        } completion:nil];
    }];
    
}



#pragma mark ---- 点击完成按钮的方法 ------
- (void)finishAction
{
//    [_timerRun invalidate];
    if (_meters / 1000 < 0.01) {
        _alertController = [UIAlertController alertControllerWithTitle:@"提示" message:@"您还未开始跑步，确定结束吗?" preferredStyle:UIAlertControllerStyleAlert];
    } else if (_meters / 1000 < 1){
        _alertController = [UIAlertController alertControllerWithTitle:@"提示" message:@"您的跑步少于1公里将不会被记录，确定结束吗?" preferredStyle:UIAlertControllerStyleAlert];
    } else {
    _alertController = [UIAlertController alertControllerWithTitle:@"提示" message:@"确定结束嘛" preferredStyle:UIAlertControllerStyleAlert];
        }
    UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"好的" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        [ [ UIApplication sharedApplication] setIdleTimerDisabled:NO] ;

        _isRun = NO;
//        _setView.hidden = YES;
        // 只有跑步距离大于1公里才记录
        if (_meters / 1000 >= 1) {
            _NumberTime ++;
            _allMeters += _meters;
        }
        //2222

        [UIView transitionWithView:_afterView duration:1 options:UIViewAnimationOptionTransitionFlipFromLeft animations:^{
            [UIView animateWithDuration:1 animations:^{
                _stopRun.frame = CGRectMake(KWIDTH / 2 - 25, KHEIGHT, 50, 50);
                _setView.frame = CGRectMake(KWIDTH, KHEIGHT - 120, 80, 40);
            }];
            _finishButton.hidden = YES;
            _continueButton.hidden = YES;
        } completion:^(BOOL finished) {
            [_afterView removeFromSuperview];
            _startRun.hidden = NO;
            [self numberView];
            self.navigationController.tabBarController.tabBar.frame = CGRectMake(0, KHEIGHT - 49, KWIDTH, 49);

    }];
}];
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
//         [_timerRun setFireDate:[NSDate distantPast]];
        [self continueAction];
    }];
    [_alertController addAction:okAction];
    [_alertController addAction:cancelAction];
    cancelAction.enabled = YES;
    [self presentViewController:_alertController animated:YES completion:nil];
    [_animationTimer invalidate];

}

#pragma mark ----- 点击继续按钮 ----
- (void)continueAction
{
    [_animationTimer invalidate];
    [_timerRun setFireDate:[NSDate distantPast]];
    _finishButton.hidden = YES;
    _continueButton.hidden = YES;
    [UIView animateWithDuration:1 animations:^{
        _stopRun.frame = CGRectMake(KWIDTH / 2 - 25, KHEIGHT - 120, 50, 50);
    }];
}

#pragma mark ------- 定位按钮 ------
- (void)loactionAction
{

    [_locationManager startUpdatingLocation];

}

#pragma mark ------ 设置按钮 -----
- (void)setButtonAction:(UIButton *)button
{
    
    [UIView animateWithDuration:0.5 animations:^{
        _backView.hidden = NO;
        _musicView.frame = CGRectMake(0, KHEIGHT - 170, KWIDTH, 170);
    }];
 
}

#pragma mark  ----- 手势和返回按钮的方法 ----
- (void)tapAction
{
    [UIView animateWithDuration:0.5 animations:^{
        _backView.hidden = YES;
        _tabelView.frame = CGRectMake(KWIDTH / 3 * 2 + KWIDTH / 3 / 2 , KHEIGHT - 150, 0, 0);
        _musicView.frame = CGRectMake(0, KHEIGHT, KWIDTH, 170);
        
    }];
    _isDik = NO;
    
}


- (void)chooseButtonAction
{
    MusicChooseViewController *musicChooseVc = [[MusicChooseViewController alloc]init];
    musicChooseVc.controllerStr = @"run";
    [self.navigationController pushViewController:musicChooseVc animated:YES];
}

- (void)playButtonAction
{
    [ [ UIApplication sharedApplication] setIdleTimerDisabled:YES ];
    [UIView animateWithDuration:0.5 animations:^{
        _backView.hidden = YES;
        _tabelView.frame = CGRectMake(KWIDTH / 3 * 2 + KWIDTH / 3 / 2 , KHEIGHT - 150, 0, 0);
        _musicView.frame = CGRectMake(0, KHEIGHT, KWIDTH, 170);
        
    }];
    _isDik = NO;
    
}
- (void)mapButtonAction
{
    if (_isDik == NO) {
        [UIView animateWithDuration:0.5 animations:^{
            _tabelView.frame = CGRectMake(KWIDTH / 3 * 2 + KWIDTH / 3 / 2 - 49, KHEIGHT - 250, 98, 78);
        }];
    } else {
        [UIView animateWithDuration:0.5 animations:^{
            _tabelView.frame = CGRectMake(KWIDTH / 3 * 2 + KWIDTH / 3 / 2 , KHEIGHT - 150, 0, 0);
        }];
    }
    _isDik = !_isDik;

}
- (void)configureLocationManager
{
    
    _locationManager = [[CLLocationManager alloc] init];
    if (![CLLocationManager locationServicesEnabled]) {
        NSLog(@"定位服务当前可能没打开");
        return;
    }
    
    // 如果没有授权则请求用户授权
    if ([CLLocationManager authorizationStatus] == kCLAuthorizationStatusNotDetermined) {
        [_locationManager requestWhenInUseAuthorization];
        
    } else if ([CLLocationManager authorizationStatus] == kCLAuthorizationStatusAuthorizedWhenInUse){
        _locationManager.delegate = self;
        _locationManager.desiredAccuracy = kCLLocationAccuracyBest; // 设置定位精度
        _locationManager.distanceFilter = 10; // 10米定位一次
        [_locationManager startUpdatingLocation];
        [_locationManager startMonitoringSignificantLocationChanges];
    }
}




- (void)drawLineWithLocationArray:(NSArray *)locationArray
{
    // define minimum, maximum points
    MKMapPoint northEastPoint = MKMapPointMake(0.f, 0.f);
    MKMapPoint southWestPoint = MKMapPointMake(0.f, 0.f);
    
    MKMapPoint *pointArr=malloc(sizeof(CLLocationCoordinate2D)* locationArray.count);
    for (int idx=0; idx<locationArray.count; idx++) {
        CLLocation *location=[locationArray objectAtIndex:idx];
        CLLocationDegrees latitude=location.coordinate.latitude;
        CLLocationDegrees longitude=location.coordinate.longitude;
        
        CLLocationCoordinate2D coordinate=CLLocationCoordinate2DMake(latitude, longitude);
        MKMapPoint point=MKMapPointForCoordinate(coordinate);
        
        // if it is the first point, just use them, since we have nothing to compare to yet.
        if (idx == 0) {
            northEastPoint = point;
            southWestPoint = point;
        } else {
            if (point.x > northEastPoint.x)
                northEastPoint.x = point.x;
            if(point.y > northEastPoint.y)
                northEastPoint.y = point.y;
            if (point.x < southWestPoint.x)
                southWestPoint.x = point.x;
            if (point.y < southWestPoint.y)
                southWestPoint.y = point.y;
        }
        pointArr[idx]=point;
        
    }
    
    if (_routeLine) {
        [_mapView removeOverlay:_routeLine];
    }
    
    _routeLine = [MKPolyline polylineWithPoints:pointArr count:locationArray.count];
    
    //add the overlay to the map
    if (_routeLine != nil) {
        [_mapView addOverlay:_routeLine];
    }
    
    //clear the memory
    free(pointArr);
    
    
}

#pragma mark core location
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations{
    
    
    //    NSLog(@"arr=%@",locations);
    //    去偏移量
    CLLocation *newloction=locations.lastObject;
    newloction=[newloction locationMarsFromEarth];
    
    CLLocationDistance distance = [newloction distanceFromLocation:_oldLocation];
    _oldLocation = newloction;
    if (distance >= 0) {
        _meters += distance;

    } else {
        _meters -= distance;
    }
    
    _lengthLabel.text = [NSString stringWithFormat:@"%.2f", _meters / 1000];
    
    
    //    大头针
    //    PlaceModel *place=[[PlaceModel alloc] init];
    //    place.coordinate=newloction.coordinate;
    //    place.title=@"您当前位置";
    //    place.subtitle=@"";
    //    [self.mapView addAnnotation:place];
    CLLocation *loaction = [locations firstObject]; // 取第一个位置
    
    
//    CLLocationCoordinate2D coordinate = loaction.coordinate; // 位置坐标
    
//    NSString *newstr = [NSString stringWithFormat:@"%.4f", newloction.coordinate.latitude];
//    NSLog(@"netLat:%@", newstr);
//    NSString *strLat = [NSString stringWithFormat:@"%.4f", coordinate.latitude];
//    NSString *strLng = [NSString stringWithFormat:@"%.4f", coordinate.longitude];
//    NSLog(@"lat:%@  lng:%@", strLat, strLng);
    
    NSLog(@"行走速度：%f", newloction.speed);
    if (loaction.speed < 0) {
        _speedLabel.text = @"0.00";
    } else {
    _speedLabel.text = [NSString stringWithFormat:@"%.2f", loaction.speed * 60 / 1000];
    }
    
    
    //地图显示点
    MKCoordinateRegion region;
    region=MKCoordinateRegionMakeWithDistance(newloction.coordinate, 300, 300);
        if (![[NSUserDefaults standardUserDefaults] boolForKey:@"everLaunched"])
        {
            [self.mapView setRegion:region animated:YES];

        } else {
            [self.mapView setRegion:region animated:NO];

        }
    
    //    将经纬度加入数组
    [_rePlayArray addObject:newloction];
    if (_isRun == YES) {
        //    调用画线
        [self drawLineWithLocationArray:_rePlayArray];
    }
    


}

//- (CLLocationDistance)distanceFromLocation:(const CLLocation *)location
//{
//    
//}

#pragma mark--mapview delegate
- (MKOverlayView *)mapView:(MKMapView *)mapView viewForOverlay:(id<MKOverlay>)overlay
{
    MKOverlayView *overlayView=nil;
    if (overlay == _routeLine) {
        
        _routeLineView = [[MKPolylineView alloc]initWithPolyline:_routeLine];
        _routeLineView.fillColor=[UIColor blueColor];
        _routeLineView.strokeColor = [UIColor blueColor];
        _routeLineView.lineWidth = 5;
        overlayView=_routeLineView;
        
    }
    return overlayView;
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    //开始定位
    //     [_locationManager startUpdatingLocation];
    [UIView animateWithDuration:0.5 animations:^{
        _backView.hidden = YES;
        _tabelView.frame = CGRectMake(KWIDTH / 3 * 2 + KWIDTH / 3 / 2 , KHEIGHT - 150, 0, 0);
        _musicView.frame = CGRectMake(0, KHEIGHT, KWIDTH, 170);
        
    }];
    _isDik = NO;
    
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    //停止定位
    [_locationManager stopUpdatingLocation];
}
- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    
    self.mapView = nil;
    self.routeLine = nil;
    self.routeLineView = nil;
}


@end





/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/


